package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

public class thirdclass extends AppCompatActivity implements Runnable {
    private static final String TAG="Rate";
    TextView show;
    private float dollar_rate=0.1f;
    private float euro_rate=0.05f;
    private float won_rate=50f;
    Handler handler;
    @Override
    protected void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_ratechange);
        show=findViewById(R.id.result);
        SharedPreferences sharedPreferences=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollar_rate=sharedPreferences.getFloat("dollar_23rate",0.1f);
        euro_rate=sharedPreferences.getFloat("euro_rate",0.2f);
        won_rate=sharedPreferences.getFloat("won_rate",123.0f);
        handler =new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==5){
                    //String str=(String) msg.obj;
                    Bundle bundle=(Bundle)msg.obj;
                    dollar_rate=bundle.getFloat("dollar");
                    euro_rate=bundle.getFloat("euro");
                    won_rate=bundle.getFloat("won");
                    Toast.makeText(thirdclass.this,"汇率更新完成",Toast.LENGTH_SHORT).show();
                    //show.setText(str);
                }
                super.handleMessage(msg);
            }
        };
        //启动线程
        Thread t=new Thread(this);
        t.start();//this.run()

    }
    public void click(View btn){
        EditText input=findViewById(R.id.rmb);
        String inpStr=input.getText().toString();
        try {
        float rmb=Float.parseFloat(inpStr);
        float result=0.0f;

            if (btn.getId() == R.id.btn_dollar) {
                result = rmb * dollar_rate;

            } else if (btn.getId() == R.id.btn_euro) {
                result = rmb *euro_rate;
            } else if (btn.getId() == R.id.btn_won) {
                result = rmb * won_rate;
            }
            show.setText(String.valueOf(result));
        }catch (NumberFormatException ex){
            Toast.makeText(this, "请输入正确数据", Toast.LENGTH_LONG).show();//弹出提示信息
        }
    }
    @Override
    public void run() {
        URL url=null;
        String html="";
        Bundle retbuddle=new Bundle();
        try {
            //     url=new URL("https://www.exchange-rates.org/zh/current-rates/cny");
            //     HttpURLConnection http=(HttpURLConnection) url.openConnection();
            //     InputStream in=http.getInputStream();
            //     html=inputStream2String(in);
            Document doc= (Document) Jsoup.connect("https://chl.cn/?jinri").get();
            Element table=doc.getElementsByTagName("table").item();
            Elements rows=table.getElementsByTagName("tr");
            rows.remove(0);
            for(Element row:rows){


                Elements tds=row.getElementsByTagName("td");
                Element td1=tds.get();
                Element td2=tds.get(4);
                String str1=td1.text().trim();
                String str2=td2.text().trim();
                html+=(str1+"=>"+str2+"\n");
                //提取三个汇率值
                if(str1.equals("美元")){
                    retbuddle.putFloat("dollar",Float.parseFloat(str2));
                }else if(str1.equals("欧元")){
                    retbuddle.putFloat("euro",Float.parseFloat(str2));
                }else if(str1.equals("韩国元")){
                    retbuddle.putFloat("won",Float.parseFloat(str2));
            }   }
            //Element td=doc.select(#Lt > article > div.ahh > table:nth-child(3) > tbody > tr:nth-child(19) > td:nth-child(3))

        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        Message msg=handler.obtainMessage(5,"Hello from thread");
        handler.sendMessage(msg);
        private String inputStream2String(InputStream inputStream)throws IOException{
            final int bufferSize=1024;
            final char[]buffer=new char[bufferSize];
            final StringBuilder out=new StringBuilder();
            Reader in=new InputStreamReader(InputStream,"utf-8");
            while (true){
                int rsz=in.read(buffer,0,buffer.length);
                if(rsz<0)
                    break;
                out.append(buffer,0,rsz);

            }
            return out.toString();
        }

    }
    public void  clickOpen(View btn){
        Intent config=new Intent(this, ConfigActivity.class);
        //传递参数

        config.putExtra("dollar_rate_key",dollar_rate);
        config.putExtra("euro_rate_key",euro_rate);
        config.putExtra("won_rate_key",won_rate);
        Log.i(TAG,"clickOpen:dollar_rate="+dollar_rate);
        Log.i(TAG,"clickOpen:euro_rate="+euro_rate);
        Log.i(TAG,"clickOpen:won_rate="+won_rate);

        //startActivity(config);
        //Intent intent=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:87092173"));
        //startActivity(intent);  //跳转拨号页面效果
        startActivityForResult(config,3);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode==3&&resultCode==6){
            Bundle bdl=data.getExtras();
            dollar_rate=bdl.getFloat("key_dollar2");
            euro_rate=bdl.getFloat("key_euro2");
            won_rate=bdl.getFloat("key_won2");
            Log.i(TAG,"onActivityResult:dollarRate="+dollar_rate);
            Log.i(TAG,"onActivityResult:euroRate="+euro_rate);
            Log.i(TAG,"onActivityResult:wonRate="+won_rate);
        }

    }
    //public void click5(View btn){
        //Intent intentPhone=new Intent(Intent.ACTION_CALL, Uri.parse("tel:87092173"));
        //startActivity(intentPhone);
    //    Intent jdintent=new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.jd.com"));
    //    startActivity(jdintent);
    //}
}
